<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import sider from './HrSider.vue'
import heade from './HrHeader.vue'
import timeselect from './TimeSelect.vue'
import { getHrRecordList, deleteHrRecord, batchDeleteHrRecords, updateHrRecord } from '@/api/hr.js'

// 人事操作日志数据
const operationLogs = reactive([])

// 加载状态
const loading = ref(false)
const error = ref('')

// 筛选与UI状态
const searchQuery = ref('')
const departmentFilter = ref('all')
const timeRange = ref({ startDate: '', endDate: '' })
const isBatchMode = ref(false)
const selectedLogIds = ref([])

// 获取操作日志列表
const fetchOperationLogs = async () => {
  loading.value = true
  error.value = ''
  try {
    const response = await getHrRecordList()
    if (response.data.code === 1) {
      // 清空并重新填充数组
      operationLogs.splice(0, operationLogs.length, ...response.data.data)
    } else {
      throw new Error(response.data.msg || '获取日志数据失败')
    }
  } catch (err) {
    error.value = err.message || '获取日志数据失败'
    console.error('获取日志数据失败:', err)
  } finally {
    loading.value = false
  }
}

// 初始化数据
onMounted(() => {
  fetchOperationLogs()
})

// 编辑日志模态框状态
const isEditLogModalVisible = ref(false)
const editingLogModal = reactive({
  record_id: '',
  user_id: '',
  operator_id: '',
  operation_type: '',
  operation_field: '',
  old_value: '',
  new_value: '',
  operation_time: '',
  operation_ip: '',
  remark: '',
  // 显示用的字段
  operator: '',
  target: '',
  department: ''
})

// 计算属性：根据所有条件筛选日志
const filteredLogs = computed(() => {
  let result = operationLogs

  // 1. 按部门筛选
  if (departmentFilter.value !== 'all') {
    result = result.filter(log => log.department === departmentFilter.value)
  }

  // 2. 按时间范围筛选
  if (timeRange.value.startDate) {
    result = result.filter(log => new Date(log.operation_time) >= new Date(timeRange.value.startDate))
  }
  if (timeRange.value.endDate) {
    result = result.filter(log => new Date(log.operation_time) <= new Date(timeRange.value.endDate + ' 23:59:59'))
  }

  // 3. 按员工姓名搜索
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(log => 
      (log.target_username && log.target_username.toLowerCase().includes(query)) ||
      (log.operator_username && log.operator_username.toLowerCase().includes(query))
    )
  }

  return result
})

// --- 函数定义 ---

// 切换批量管理模式
const toggleBatchMode = () => {
  isBatchMode.value = !isBatchMode.value
  selectedLogIds.value = []
}

// 刷新日志列表
const refreshLogs = async () => {
  await fetchOperationLogs()
}

// 全选/取消全选 (基于筛选后的结果)
const handleSelectAll = () => {
  if (selectedLogIds.value.length === filteredLogs.value.length) {
    selectedLogIds.value = []
  } else {
    selectedLogIds.value = filteredLogs.value.map(log => log.record_id)
  }
}

// 切换单个日志选中状态
const toggleLogSelection = (logId) => {
  const index = selectedLogIds.value.indexOf(logId)
  if (index > -1) {
    selectedLogIds.value.splice(index, 1)
  } else {
    selectedLogIds.value.push(logId)
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectedLogIds.value.length === 0) return

  if (confirm(`确定要删除选中的 ${selectedLogIds.value.length} 条日志记录吗？`)) {
    loading.value = true
    try {
      const response = await batchDeleteHrRecords(selectedLogIds.value)
      if (response.data.code === 1) {
        // 从本地列表中删除
        for (let i = operationLogs.length - 1; i >= 0; i--) {
          if (selectedLogIds.value.includes(operationLogs[i].record_id)) {
            operationLogs.splice(i, 1)
          }
        }
        selectedLogIds.value = []
        isBatchMode.value = false
      } else {
        throw new Error(response.data.msg || '批量删除失败')
      }
    } catch (err) {
      error.value = err.message || '批量删除失败'
      console.error('批量删除失败:', err)
      alert('删除失败：' + err.message)
    } finally {
      loading.value = false
    }
  }
}

// 单个删除日志
const deleteLog = async (recordId) => {
  if (confirm('确定要删除这条日志记录吗？')) {
    loading.value = true
    try {
      const response = await deleteHrRecord(recordId)
      if (response.data.code === 1) {
        const index = operationLogs.findIndex(l => l.record_id === recordId)
        if (index > -1) {
          operationLogs.splice(index, 1)
        }
      } else {
        throw new Error(response.data.msg || '删除失败')
      }
    } catch (err) {
      error.value = err.message || '删除失败'
      console.error('删除失败:', err)
      alert('删除失败：' + err.message)
    } finally {
      loading.value = false
    }
  }
}

// 恢复员工（暂时保留前端逻辑，实际应该调用后端API）
const restoreEmployee = () => {
  alert('恢复员工功能需要后端支持，请联系管理员')
  // TODO: 实现恢复员工的后端API
}

// 打开编辑日志模态框
const openEditLogModal = (log) => {
  Object.assign(editingLogModal, log)
  isEditLogModalVisible.value = true
}

// 保存编辑日志
const saveEditLogModal = async () => {
  loading.value = true
  try {
    const response = await updateHrRecord(editingLogModal.record_id, editingLogModal.remark)
    if (response.data.code === 1) {
      const index = operationLogs.findIndex(l => l.record_id === editingLogModal.record_id)
      if (index !== -1) {
        operationLogs[index].remark = editingLogModal.remark
      }
      isEditLogModalVisible.value = false
    } else {
      throw new Error(response.data.msg || '更新失败')
    }
  } catch (err) {
    error.value = err.message || '更新失败'
    console.error('更新失败:', err)
    alert('更新失败：' + err.message)
  } finally {
    loading.value = false
  }
}

// 关闭编辑日志模态框
const closeEditLogModal = () => {
  isEditLogModalVisible.value = false
}
</script>

<template>
  <div class="admin-layout">
    <!-- 顶栏 -->
    <div class = topbar>
      <heade/>
    </div>
    <!-- 侧边栏 -->
    <div class = sidebar>
      <div class = sidebar-menu>
        <sider/>
      </div>
    </div>
    <!-- 主内容区容器 -->
    <div class="content-wrapper">
      <div class="main-content">
        <div class="content-section">
          <div class = "section-header">
            <h3>人事操作日志</h3>
            <!--头部栏-->
            <div class="header-actions">
              <div class = "filter-buttons">
                <!-- 刷新按钮 -->
                <button class="filter-btn" @click="refreshLogs" :disabled="loading">
                  {{ loading ? '加载中...' : '刷新' }}
                </button>
                <!-- 批量管理按钮 -->
                <button class="filter-btn" :class="{ active: isBatchMode }" @click="toggleBatchMode">
                  {{ isBatchMode ? '退出批量' : '批量管理' }}
                </button>

                <!-- 批量操作按钮 -->
                <template v-if="isBatchMode && selectedLogIds.length > 0">
                  <button class="filter-btn batch-btn delete-btn" @click="batchDelete">
                    删除 ({{ selectedLogIds.length }})
                  </button>
                </template>

                <!-- 全选框 -->
                <label v-if="isBatchMode" class="select-all-label">
                  <input
                    type="checkbox"
                    :checked="selectedLogIds.length === filteredLogs.length && filteredLogs.length > 0"
                    @change="handleSelectAll"
                  >
                  全选
                </label>

                <!-- 筛选控件 -->
                <select v-model="departmentFilter" class="dept-select">
                  <option value="all">全部部门</option>
                  <option value="技术部">技术部</option>
                  <option value="市场部">市场部</option>
                  <option value="财务部">财务部</option>
                  <option value="行政部">行政部</option>
                </select>
                <el-input v-model="searchQuery" style="width: 240px;" placeholder="请输入员工姓名" />
                <timeselect v-model="timeRange"/>
              </div>
            </div>
          </div>
          <!-- 错误提示 -->
          <div v-if="error" class="error-message">
            {{ error }}
            <button @click="error = ''" class="close-error">×</button>
          </div>
          <!--列表主体-->
          <div class="work-list">
            <div class="work-item">
              <!-- 加载状态 -->
              <div v-if="loading" class="loading-state">
                <div class="loading-spinner"></div>
                <p>加载中...</p>
              </div>
              <div v-else-if="filteredLogs.length === 0" class="empty-state">
                <div class="empty-icon">📋</div>
                <p>暂无符合条件的日志记录</p>
              </div>
              <div v-else>
                <div
                  v-for="log in filteredLogs"
                  :key="log.record_id"
                  class="log-item"
                  :class=" { 'selected': selectedLogIds.includes(log.record_id) }"
                  @click.stop
                >
                  <!-- 批量选择框 -->
                  <div v-if="isBatchMode" class="batch-checkbox">
                    <input
                      type="checkbox"
                      :checked="selectedLogIds.includes(log.record_id)"
                      @change="toggleLogSelection(log.record_id)"
                    >
                  </div>

                  <div class="log-content">
                    <div class="log-header">
                      <span class="log-action" :class="{
                        'added': log.operation_type === '增',
                        'modified': log.operation_type === '改',
                        'deleted': log.operation_type === '删'
                      }">{{ log.operation_type === '增' ? '新增' : log.operation_type === '改' ? '修改' : '删除' }}</span>
                      <span class="log-time">{{ log.operation_time }}</span>
                    </div>
                    <p class="log-target">字段：{{ log.operation_field }} | 目标用户ID：{{ log.user_id }}</p>
                    <p class="log-operator">操作人 ID：{{ log.operator_id }} | 旧值：{{ log.old_value || '无' }} → 新值：{{ log.new_value || '无' }}</p>
                    <p v-if="log.remark" class="log-remark">备注：{{ log.remark }}</p>
                  </div>

                  <!-- 单个操作按钮 -->
                  <div v-if="!isBatchMode" class="log-actions">
                    <button class="action-btn edit-btn" @click="openEditLogModal(log)">修改备注</button>
                    <button class="action-btn delete-btn" @click="deleteLog(log.record_id)">删除</button>
                    <button v-if="log.operation_type === '删'" class="action-btn restore-btn" @click="restoreEmployee()">恢复</button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑日志模态框 -->
    <div v-if="isEditLogModalVisible" class="profile-modal" @click.self="closeEditLogModal">
      <div class="profile-content">
        <div class="profile-header">
          <h3>修改日志</h3>
          <button class="close-btn" @click="closeEditLogModal">×</button>
        </div>
        <div class="profile-body">
          <div class="detail-row">
            <label>记录ID：</label>
            <input type="text" v-model="editingLogModal.record_id" disabled>
          </div>
          <div class="detail-row">
            <label>操作类型：</label>
            <input type="text" v-model="editingLogModal.operation_type" disabled>
          </div>
          <div class="detail-row">
            <label>操作字段：</label>
            <input type="text" v-model="editingLogModal.operation_field" disabled>
          </div>
          <div class="detail-row">
            <label>目标用户ID：</label>
            <input type="text" v-model="editingLogModal.user_id" disabled>
          </div>
          <div class="detail-row">
            <label>操作人 ID：</label>
            <input type="text" v-model="editingLogModal.operator_id" disabled>
          </div>
          <div class="detail-row">
            <label>旧值：</label>
            <input type="text" v-model="editingLogModal.old_value" disabled>
          </div>
          <div class="detail-row">
            <label>新值：</label>
            <input type="text" v-model="editingLogModal.new_value" disabled>
          </div>
          <div class="detail-row">
            <label>操作时间：</label>
            <input type="text" v-model="editingLogModal.operation_time" disabled>
          </div>
          <div class="detail-row">
            <label>操作 IP：</label>
            <input type="text" v-model="editingLogModal.operation_ip" disabled>
          </div>
          <div class="detail-row">
            <label>备注：</label>
            <textarea v-model="editingLogModal.remark"></textarea>
          </div>
          <div class="profile-actions">
            <button class="profile-btn save-btn" @click="saveEditLogModal">保存</button>
            <button class="profile-btn" @click="closeEditLogModal">取消</button>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<style scoped>
/* --- 布局样式 --- */
.admin-layout {
  display: flex;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}
.content-wrapper {
  margin-top: 50px;
  flex: 1;
  display: flex;
  flex-direction: column;
}
.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}
.content-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  display: flex;
  flex-direction: column;
  height: 100%;
}
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25px 30px;
  border-bottom: 1px solid #e8e8e8;
}
.section-header h3 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #333;
}
/* --- 头部筛选样式 --- */
.header-actions {
  display: flex;
  align-items: center;
}
.filter-buttons {
  display: flex;
  gap: 10px;
  align-items: center;
}
.filter-btn, .dept-select {
  padding: 8px 16px;
  border: 1px solid #d9d9d9;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
}
.filter-btn:hover, .dept-select:hover {
  border-color: #667eea;
}
.filter-btn.active {
  background: #667eea;
  border-color: #667eea;
  color: white;
}
.filter-btn.delete-btn:hover {
  border-color: #ff4d4f;
  color: #ff4d4f;
}
.select-all-label {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  margin-left: 10px;
}

/* --- 列表样式 --- */
.work-list {
  flex: 1;
  overflow-y: auto;
}
.work-item {
  width: 100%;
}
.log-item {
  padding: 20px 30px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 15px;
  position: relative;
}
.log-item:hover { background: #f8f9fa; }
.log-item.selected {
  background: #f0f9ff;
}
.log-item.selected::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background: #1890ff;
}
.batch-checkbox { flex-shrink: 0; }
.batch-checkbox input[type="checkbox"] {
  width: 16px;
  height: 16px;
  cursor: pointer;
}
.log-content { flex: 1; min-width: 0; }
.log-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
.log-action {
  font-weight: 500;
  color: #1890ff;
}
.log-action.added { color: #52c41a; }
.log-action.modified { color: #faad14; }
.log-action.deleted { color: #ff4d4f; }
.log-time { font-size: 12px; color: #999; }
.log-target, .log-operator, .log-remark {
  margin: 0;
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.log-remark {
  margin-top: 5px;
  font-style: italic;
  color: #999;
}
.log-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}
.action-btn {
  padding: 4px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s ease;
  color: white;
}
.action-btn.edit-btn { background: #1890ff; }
.action-btn.edit-btn:hover { background: #40a9ff; }
.action-btn.delete-btn { background: #ff4d4f; }
.action-btn.delete-btn:hover { background: #ff7875; }
.action-btn.restore-btn { background: #52c41a; }
.action-btn.restore-btn:hover { background: #73d13d; }

/* --- 空状态 --- */
.empty-state {
  padding: 60px;
  text-align: center;
  color: #999;
}
.empty-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

/* --- 加载状态 --- */
.loading-state {
  padding: 60px;
  text-align: center;
  color: #999;
}
.loading-spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 15px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* --- 错误提示 --- */
.error-message {
  margin: 20px 30px;
  padding: 12px 20px;
  background: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 6px;
  color: #ff4d4f;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.close-error {
  background: none;
  border: none;
  color: #ff4d4f;
  font-size: 20px;
  cursor: pointer;
  padding: 0;
  width: 20px;
  height: 20px;
  line-height: 1;
}
.close-error:hover {
  color: #ff7875;
}

/* --- 模态框样式 --- */
.profile-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
.profile-content {
  background: #fff;
  padding: 0;
  border-radius: 12px;
  width: 500px;
  box-shadow: 0 5px 25px rgba(0,0,0,0.2);
  animation: modalFadeIn 0.3s ease-out;
}
@keyframes modalFadeIn {
  from { opacity: 0; transform: translateY(-20px); }
  to { opacity: 1; transform: translateY(0); }
}
.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid #e8e8e8;
}
.profile-header h3 { margin: 0; font-size: 18px; color: #333; }
.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #aaa;
  cursor: pointer;
  line-height: 1;
  padding: 0;
  width: 30px;
  height: 30px;
}
.close-btn:hover { color: #333; }
.profile-body { padding: 30px; text-align: left; }
.detail-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
}
.detail-row label {
  width: 100px;
  font-weight: 500;
  color: #333;
  margin-right: 15px;
  flex-shrink: 0;
}
.detail-row input,
.detail-row select,
.detail-row textarea {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
}
.detail-row textarea { min-height: 80px; resize: vertical; }
.profile-actions {
  margin-top: 30px;
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}
.profile-btn {
  padding: 10px 20px;
  border: 1px solid #d9d9d9;
  background: #fff;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}
.profile-btn:hover {
  background-color: #f5f5f5;
  border-color: #667eea;
  color: #667eea;
}
.profile-btn.save-btn {
  background: #1890ff;
  color: white;
  border-color: #1890ff;
}
.profile-btn.save-btn:hover {
  background: #40a9ff;
  border-color: #40a9ff;
}

/* --- 保留侧边栏和顶栏样式 --- */
.sidebar {
  width: 260px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  box-sizing: border-box;
  flex-direction: column;
  box-shadow: 2px 0 10px rgba(0,0,0,0.1);
}
.sidebar-header { padding: 30px 20px; border-bottom: 1px solid rgba(255,255,255,0.1); }
.sidebar-header h2 { margin: 0 0 5px 0; font-size: 20px; font-weight: 600; }
.sidebar-header p { margin: 0; font-size: 14px; opacity: 0.8; }
.sidebar-menu { flex: 1; padding: 20px 0; }
.menu-item { display: flex; align-items: center; padding: 15px 25px; cursor: pointer; transition: all 0.3s ease; border-left: 3px solid transparent; }
.menu-item:hover { background: rgba(255,255,255,0.1); }
.menu-item.active { background: rgba(255,255,255,0.2); border-left-color: white; }
.menu-icon { font-size: 20px; margin-right: 15px; width: 25px; text-align: center; }
.menu-text { font-size: 15px; font-weight: 500; }

.topbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  padding: 0 30px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  z-index: 10;
}
</style>
